package ca.etsmtl.log240.financej;
/*
 * Category.java
 *
 * Created on March 9, 2008, 6:03 PM
 */

import java.sql.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.*;

/**
 *
 * @author  rovitotv
 */
public class Category extends javax.swing.JDialog {

    private Connection conn = null;
    private CategoryListTableModel dataModel;

    /** Creates new form Category */
    public Category(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        CategoryListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public void SetDBConnection(Connection DBConn) {
        conn = DBConn;
        dataModel = new CategoryListTableModel(conn);
        CategoryListTable.setModel(dataModel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        CloseButton = new javax.swing.JButton();
        DeleteCategoryButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        AddCategoryButton = new javax.swing.JButton();
        NameTextField = new javax.swing.JTextField();
        DescriptionTextField = new javax.swing.JTextField();
        BudgetTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        CategoryListTable = new javax.swing.JTable();

        setTitle("Categories");

        CloseButton.setText("Close");
        CloseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CloseButtonActionPerformed(evt);
            }
        });

        DeleteCategoryButton.setText("Delete Category");
        DeleteCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteCategoryButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Name:");

        jLabel2.setText("Description:");

        jLabel3.setText("Budget:");

        AddCategoryButton.setText("Add Category");
        AddCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddCategoryButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(DescriptionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                    .addComponent(NameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(BudgetTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                        .addComponent(AddCategoryButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(NameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(DescriptionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(BudgetTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(AddCategoryButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        CategoryListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Name", "Description", "Budget"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(CategoryListTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(293, Short.MAX_VALUE)
                .addComponent(DeleteCategoryButton)
                .addGap(18, 18, 18)
                .addComponent(CloseButton)
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CloseButton)
                    .addComponent(DeleteCategoryButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void AddCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddCategoryButtonActionPerformed
        int ReturnCode;
        String BudgetValue;
        float Budget;
        
        BudgetValue = BudgetTextField.getText();
        Budget = Float.valueOf(BudgetValue.trim()).floatValue();
        
        ReturnCode = dataModel.AddCategory(NameTextField.getText(), DescriptionTextField.getText(), Budget);
        if (ReturnCode == 0) {
            NameTextField.setText("");
            DescriptionTextField.setText("");
            BudgetTextField.setText("");
        } else {
            JOptionPane.showMessageDialog(this,
                    "Error Adding category to database.  Make sure the category name you specified does not already exist.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_AddCategoryButtonActionPerformed

    private void CloseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_CloseButtonActionPerformed

    private void DeleteCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteCategoryButtonActionPerformed
        if (CategoryListTable.getSelectionModel().getLeadSelectionIndex() >= 0) {
            System.out.println("delete row:" + CategoryListTable.getSelectionModel().getLeadSelectionIndex());
            dataModel.DeleteCategory(CategoryListTable.getSelectionModel().getLeadSelectionIndex());
        } else { //nothing selected give error messge
            JOptionPane.showMessageDialog(this,
                    "No category selected to delete, please select a category then click the delete button.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_DeleteCategoryButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Category dialog = new Category(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddCategoryButton;
    private javax.swing.JTextField BudgetTextField;
    private javax.swing.JTable CategoryListTable;
    private javax.swing.JButton CloseButton;
    private javax.swing.JButton DeleteCategoryButton;
    private javax.swing.JTextField DescriptionTextField;
    private javax.swing.JTextField NameTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}

class CategoryListTableModel extends AbstractTableModel {

    private String[] columnNames = {"Name", "Description", "Budget"};
    private Connection conn = null;

    public CategoryListTableModel(Connection DBConn) {
        conn = DBConn;
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        ResultSet AccountResult;
        Statement s;

        if (conn != null) {
            try {
                s = conn.createStatement();
                AccountResult = s.executeQuery("select count(name) from category");
                while (AccountResult.next()) {
                    return AccountResult.getInt(1);
                }
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in CategoryListTableModel getRowCount");
                e.printStackTrace();
            }
        }

        return 0;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        ResultSet CategoryResult;
        Statement s;
        int CurrentRow = 0;

        if (conn != null) {
            try {
                s = conn.createStatement();
                CategoryResult = s.executeQuery("select * from category order by name");
                while (CategoryResult.next()) {
                    if (CurrentRow == row) {
                        if (col == 0) {
                            return CategoryResult.getString(1);
                        } else if (col == 1) {
                            return CategoryResult.getString(2);
                        } else if (col == 2) {
                            return CategoryResult.getFloat(3);
                        }
                    }
                    CurrentRow++;
                }
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in CategoryListTableModel getValueAt");
                e.printStackTrace();
            }
        }
        return "";
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    /*
     * Don't need to implement this method unless your table's
     * editable.
     */
    public boolean isCellEditable(int row, int col) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.


        if (col == 0) {
            return false;
        } else {
            return true;
        }
    }

    public void setValueAt(Object value, int row, int col) {
        String SQLString = "";

        String CategoryName;
        try {
            CategoryName = (String) getValueAt(row, 0);
            Statement s = conn.createStatement();
            if (col == 1) {
                SQLString = "update category set description ='" + (String) value + "' where name = '" + CategoryName + "'";
            } else if (col == 2) {
                String StrValue;
                
                StrValue = value.toString();
                SQLString = "update category set budget = " + StrValue + " where name = '" + CategoryName + "'";
            }
            System.out.println(SQLString);
            s.execute(SQLString);

            fireTableCellUpdated(row, col);
        } catch (Throwable e) {
            System.out.println(" . . . exception thrown: in setValueAt in Category.java");
            e.printStackTrace();
        }
    }

    public void DeleteCategory(int row) {
        Statement s;
        String CategoryName;
        String SQLString;

        if (conn != null) {
            try {
                CategoryName = (String) getValueAt(row, 0);
                s = conn.createStatement();
                SQLString = "DELETE FROM category WHERE name = '" + CategoryName + "'";
                System.out.println(SQLString);
                s.executeUpdate(SQLString);
                fireTableDataChanged();
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in CategoryTableModel DeleteAccount");
                e.printStackTrace();
            }
        }
    }

    public int AddCategory(String Name, String Description, float budget) {
        int ErrorCode = 0;
        PreparedStatement psInsert;

        try {
            psInsert = conn.prepareStatement("insert into category(name, description, budget) values(?,?,?)");
            psInsert.setString(1, Name);
            psInsert.setString(2, Description);
            psInsert.setFloat(3, budget);

            psInsert.executeUpdate();
            fireTableRowsInserted(getRowCount() + 1, getRowCount() + 1);
        } catch (Throwable e) {
            System.out.println(" . . . exception thrown: AddCategory");
            e.printStackTrace();
            ErrorCode = 1;
        }

        return ErrorCode;
    }
}

